package com.tx.github.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 描述
 * @Author：XiaoBing
 * @Date：2020/12/4 14:00
 * @Version：1.0
 */
@Controller
public class OAuth2Controller {
    private static final Logger logger = LoggerFactory.getLogger(OAuth2Controller.class);
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/authorization_code")
    public String authorization_code(String code, HttpSession session) {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "b3e6264a51ef2306a594");
        map.put("client_secret", "30da513eef15a303619e47acb859feecc279e4d5");
        map.put("state", "admin");
        map.put("code", code);
        map.put("redirect_uri", "http://localhost:8080/authorization_code");
        Map<String, String> resp = restTemplate.postForObject("https://github.com/login/oauth/access_token", map, Map.class);
        logger.info("返回值："+resp);
        HttpHeaders httpheaders = new HttpHeaders();
        httpheaders.add("Authorization", "token " + resp.get("access_token"));
        HttpEntity<?> httpEntity = new HttpEntity<>(httpheaders);
        ResponseEntity<Map> exchange = restTemplate.exchange("https://api.github.com/user", HttpMethod.GET, httpEntity, Map.class);
        logger.info("exchange.getBody() = " + exchange.getBody());
        //获取信息
        String name = (String) exchange.getBody().get("login");
        String html_url = (String) exchange.getBody().get("html_url");
        session.setAttribute("name",name);
        session.setAttribute("html_url",html_url);
        //此处应重定向
        return "success";
    }
}
